package com.ytjj.qmyx.supplychain.api.ceb.controller;

import com.alibaba.fastjson.JSONObject;
import com.ytjj.qmyx.supplychain.api.ceb.config.IgnoreUrlsConfig;
import com.ytjj.qmyx.supplychain.api.ceb.model.request.WMSCallbackCommonReq;
import com.ytjj.qmyx.supplychain.api.ceb.model.request.WMSOrderCallbackRequest;
import com.ytjj.qmyx.supplychain.api.ceb.model.request.WMSOrderExpressRequest;
import com.ytjj.qmyx.supplychain.common.api.ResultCode;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.request.BankerOrderExpressRequest;
import com.ytjj.qmyx.supplychain.common.utils.IPUtil;
import com.ytjj.qmyx.supplychain.mapper.BankerOrderMapper;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/wms/order")
public class WMSOrderController {
    @Resource
    private BankerOrderMapper bankerOrderMapper;
    @Resource
    private IgnoreUrlsConfig ignoreUrlsConfig;

    /**
     * wms 回调接口-快递单号信息
     * @return
     */
    @PostMapping("/callback/express")
    public String receiveOrderExpressCallback(WMSOrderCallbackRequest request, HttpServletRequest servletRequest) {
        String addr = IPUtil.getIpAddress(servletRequest);
        if (ignoreUrlsConfig.getIpSwitchFlag().equals(1) && !ignoreUrlsConfig.getIps().contains(addr)) {
            throw new ApiException(ResultCode.IP_FAILED);
        }
        String result = null;
        try {
            @Cleanup ServletInputStream inputStream = null;
            @Cleanup ByteArrayOutputStream outputStream = null;
            byte[] rs = new byte[1024];
            inputStream = servletRequest.getInputStream();
            outputStream = new ByteArrayOutputStream();
            int len = 0;
            byte[] req = null;
            while ((len = inputStream.read(rs)) != -1) {
                outputStream.write(rs, 0, len);
                req = outputStream.toByteArray();
            }
            result = new String(req, "UTF-8");
            log.info("result={}", result);
        }catch (Exception e){
            log.info("数据接收异常" + e, e.toString());
        }

        if (StringUtils.isEmpty(result)) {
            log.info("===result is null===");
            return "error";
        }

        try {
            String param = new String(Base64.getDecoder().decode(result), "UTF-8");
            log.info("===result transform to base64==={}", param);
            WMSCallbackCommonReq req = JSONObject.parseObject(param, WMSCallbackCommonReq.class);
            WMSOrderExpressRequest order = req.getData();
            if (null==order || StringUtils.isEmpty(order.getOrderNo())) {
                log.info("===receiveOrderExpressCallback param is error==={}", order);
                return "error";
            }

            BankerOrderExpressRequest obj = new BankerOrderExpressRequest();
            obj.setChildOrderNo(order.getOrderNo());
            obj.setExpressNo(order.getLogisticsNo());
            String companyCode = expressCodeTransfer(order.getExpressCode());
            obj.setExpressCode(companyCode);
            log.info("===更新wms订单发货信息==={}", JSONObject.toJSONString(obj));
            int num = bankerOrderMapper.updateBankerOrdersBySingle(obj);
            if (num > 0) {
                return "success";
            }
            log.info("===更新wms订单发货信息异常==={}", JSONObject.toJSONString(obj));
            return "error";
        } catch (Exception e) {
            log.error("===callback.express is error==={}", result);
            log.error("===callback.express is error==={}", e);
            return "error";
        }
    }

    private String expressCodeTransfer(String key) {
        Map<String, String> map = new HashMap();
        map.put("EMS", "ems");
        map.put("JT", "jtexpress");
        map.put("DB", "debangwuliu");
        map.put("YUNDA", "yunda");
        map.put("SF", "shunfeng");
        map.put("YTO", "yuantong");

        return null == map.get(key) ? key : map.get(key);
    }

    public static void main(String[] args) {
        String result = "eyJhcHBfa2V5IjoxMDAwMTIsImNvZGUiOiIwIiwibWV0aG9kIjoiY2JjYy5ub3RpZnkuc3lzdGVtIiwiZGF0YSI6eyJlYnBOYW1lIjoi5rex5Zyz5biC5LiA5o6i56m256uf56eR5oqA5pyJ6ZmQ5YWs5Y+4IiwiYnV5ZXJUZWxlcGhvbmUiOiIxODg3MzA1ODAx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+S4nOecgea3seWcs+W4guWuneWuieWMuuWumuWGm+WxseWkp+WOpiIsImV4dCI6e30sImJ1eWVyUmVnTm8iOiIiLCJiYXRjaE5vIjoiMTY0Njk3OTgzNDE5NSIsIm9yZGVyTm8iOiJRMjAyMTEyMTY0NTIzNTQ2IiwiY29uc2lnbmVlIjoi5rWL6K+VMSIsInRvd24iOiLpnJ7lsbHljLoiLCJsb2dpc3RpY3NDb2RlIjpudWxsLCJidXllck5hbWUiOiIiLCJzdG9yZUlkIjoiMTQ4MSIsImtleVdvcmRNYXJrTm8iOm51bGwsImNvbnNpZ25lZURpc3RyaWN0IjoiIiwibG9naXN0aWNzTmFtZSI6bnVsbCwiZ3Jvc3NXZWlnaHQiOjAuMCwibmV0V2VpZ2h0IjoiIiwicGFja2FnZUFkZHJlc3MiOiLlub/kuJzmuZvmsZ8iLCJzZW5kZXIiOiLmuZvmsZ/kv53nqI7nianmtYHkuK3lv4MiLCJjcmVhdGVUaW1lIjoiMjAyMjAzMTEgMTQ6MjM6NTQiLCJmYXN0TWFya05vIjpudWxsLCJsb2dpc3RpY3NObyI6IlRFU1RFTVMyMDIyMDMxNCIsImViY05hbWUiOiLlub/kuJzoia/ml6DpmZDlrp7kuJrmnInpmZDlhazlj7giLCJ0cmFkZU1vZGUiOiIiLCJwYXlDb2RlIjoiNDQwMzE2OUQzVyJ9LCJtZXNzYWdlIjoiIiwiYXBpVHlwZSI6IjUwMDAwMiJ9";

        try {
            String param = new String(Base64.getDecoder().decode(result), "UTF-8");

            WMSCallbackCommonReq req = JSONObject.parseObject(param, WMSCallbackCommonReq.class);
            WMSOrderExpressRequest order = req.getData();
            order.getOrderNo();
            String companyCode = order.getExpressCode();
            String logisticsNo = order.getLogisticsNo();

            BankerOrderExpressRequest obj = new BankerOrderExpressRequest();
            obj.setChildOrderNo(order.getOrderNo());
            obj.setExpressNo(logisticsNo);
            obj.setExpressCode(companyCode);
        } catch (Exception e) {
            log.error("===callback.express is error==={}", result);
            log.error("===callback.express is error==={}", e);
        }
    }

}
